import { isProd } from "./util";

/**
 * 
 * socket状态
 * 
 */
export enum SocketState {
    CONNECTING,
    OPEN,
    CLOSING,
    CLOSED
}

/**
 * 
 * 心跳检测
 * 
 */
export class HeartCheck {
    timeOut: number = 4000;
    timeOutObj: any = null;
    serverTimeOutObj: any = null;

    ws: WebSocket = null;

    constructor(ws: WebSocket) {
        this.ws = ws;
    }

    start() {
        if (!this.ws) return;
        // if(facdeCenter.game.stateType !== GameStateType.DRAWIN)

        this.timeOutObj && clearTimeout(this.timeOutObj);
        this.serverTimeOutObj && clearTimeout(this.serverTimeOutObj);

        this.timeOutObj = setTimeout(() => {
            if (!this.ws) return;
            if (this.ws && this.ws.readyState !== WebSocket.OPEN) {
                console.log('ws为null');
                return;
            }

            // socketManager.sendMessage("ping");
            this.serverTimeOutObj = setTimeout(() => {
                // console.log('主动close');
                if (!this.ws) return;
                if (this.ws.readyState === SocketState.OPEN) return;
                console.log('主动close');
                this.ws.close();
            }, this.timeOut);

        }, this.timeOut);
    }
}

export class SocketManager {

    private host: string = 'ws://denglinfeng_game-http.gateway.funshareapp.com/v1/ws/guessdraw/6502c120f278d9067f64a08e';
    private prodHost: string = 'wss://game.funshareapp.com/v1/ws/guessdraw/6502c120f278d9067f64a08e';

    private port: number = 3000;

    private _ws: WebSocket = null;
    private _heartCheck: HeartCheck = null;

    private socketMap: Map<string, WebSocket> = new Map();

    public get heartCheck() {
        return this._heartCheck;
    }

    private lockReconnect = false;
    private timeObj = null;

    public initGameServer(gameName: string, gameId: string) {
        this.host = `ws://denglinfeng_game-http.gateway.funshareapp.com/v1/ws/${gameName}/${gameId}`;
        this.prodHost = `wss://gamews.funshareapp.com/v1/ws/${gameName}/${gameId}`
    }

    /** 非绘画者接收的消息 */
    public emitSocketMessage(message: any) {
        const method = message.method;

        // to do 断线重连

        switch (method) {
            case "seat":
                // this.joinSeat(message.data.data);
                break;
        }
    }


    constructor() {
        // gameManager.socketManager = this;
    }

    /** 连接socket(http升级版) 针对绘画者专用socket通道 */
    public initSocket() {
        console.log('绘画者建立socket连接');
        console.time('startCreateWs');
        if (this._ws && this._ws.readyState === WebSocket.OPEN) {
            // if (this.socketMap.get(facdeCenter.drawerId) === this._ws) {
            //     console.log('ws已经存在');
            //     return;
            // }
        }
        this.createWs();
        if (!this._ws) {
            console.warn("初始化socket 失败");
            return;
        };

        // this.socketMap.set(facdeCenter.drawerId, this._ws);
        this._ws.onopen = () => {
            console.log('连接到了socket');
            console.timeEnd('startCreateWs');
            // this.sendMessage({ type: "start" });
            this._heartCheck.start();
        }

        this._ws.onmessage = (data: any) => {
            console.log("data is ", data);
            const realData = data.data;
            this._heartCheck.start();
            console.log("realData is ", realData);
        }

        this._ws.onerror = (err) => {
            console.log('socket error', err);
            this.reconnectWs();
        }

        this._ws.onclose = (err) => {
            console.log('socket close', err);
            this.reconnectWs();
        }

    }

    private createWs() {
        // 绘画者建立socket
        // if(facdeCenter.drawerId !== facdeCenter.userId) return;
        // const isprod = isProd();
        // console.log('isProd is ', isprod);
        // let host = this.host;
        const host = isProd() ? this.prodHost : this.host;

        try {
            // if (facdeCenter.curGameId.trim() === '0' || !facdeCenter.curGameId) {
            //     console.log('gameid is 0 or undefined', facdeCenter.curGameId);
            // }
            const wshost = host;
            console.log('链接socket', wshost);
            this._ws = new WebSocket(wshost);
            this._heartCheck = new HeartCheck(this._ws);
        } catch (e) {
            console.log("连接websoket失败", e);
            this.reconnectWs();
        }
    }

    /** 尝试重新连接socket */
    private reconnectWs(): void {
        // if()
        if (this._ws && this._ws.readyState === SocketState.OPEN) {
            return;
        }
        if (this.lockReconnect) {
            return;
        }
        this.lockReconnect = true;

        this.timeObj && clearTimeout(this.timeObj);
        this.timeObj = setTimeout(() => {
            this.createWs();
            this.lockReconnect = false;
        }, 2000);
    }

    public sendMessage(data: any) {
        if (!this._ws) return;
        if (this._ws.readyState === WebSocket.OPEN) {
            this._ws.send(JSON.stringify(data));
            // debugLog('===>上行消息发送完毕');
        } else {
            console.log('socket 没有 open,状态: ', SocketState[this._ws.readyState]);
        }
    }

    /**
     * 主动断开socket
     */
    public closeSocket() {
        if (!this._ws) return;
        this._ws.close();
        this._ws = null;
        // this.socketMap.set(facdeCenter.drawerId, null);
    }

}

export const socketManager = new SocketManager();